<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
  <title>管理员主页</title>
  <style>
    body {
      font-family: 'Arial', sans-serif;
      background-color: #f5f5f5;
      margin: 0;
      padding: 20px;
    }

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #333;
      color: white;
      padding: 15px 20px;
      margin-bottom: 20px;
      border-radius: 5px;
    }

    .username {
      font-size: 18px;
      font-weight: bold;
    }

    .edit-btn {
      background-color: #4CAF50;
      color: white;
      border: none;
      padding: 8px 15px;
      border-radius: 4px;
      cursor: pointer;
    }

    .edit-btn:hover {
      background-color: #45a049;
    }

    .user-list {
      background-color: white;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgba(0,0,0,0.1);
      padding: 20px;
      margin-bottom: 20px;
    }

    .user-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 15px;
      border-bottom: 1px solid #eee;
    }

    .user-item:last-child {
      border-bottom: none;
    }

    .user-name {
      color: #2196F3;
      cursor: pointer;
      font-weight: 500;
    }

    .user-name:hover {
      text-decoration: underline;
    }

    .user-edit-btn {
      background-color: #2196F3;
      color: white;
      border: none;
      padding: 5px 10px;
      border-radius: 3px;
      cursor: pointer;
    }

    .user-edit-btn:hover {
      background-color: #1976D2;
    }

    /* 模态框样式 */
    .modal {
      display: none;
      position: fixed;
      z-index: 1001;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.4);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 10% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 50%;
      border-radius: 5px;
    }

    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }

    .close:hover {
      color: black;
    }

    .form-group {
      margin-bottom: 15px;
    }

    .form-group label {
      display: block;
      margin-bottom: 5px;
      font-weight: 500;
    }

    .form-group input {
      width: 100%;
      padding: 8px;
      box-sizing: border-box;
      border: 1px solid #ddd;
      border-radius: 4px;
    }

    .save-btn {
      background-color: #4CAF50;
      color: white;
      border: none;
      padding: 10px 15px;
      border-radius: 4px;
      cursor: pointer;
      width: 100%;
    }

    .save-btn:hover {
      background-color: #45a049;
    }

    .history-modal {
      display: none;
      position: fixed;
      z-index: 1001;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.4);
    }

    .history-content {
      background-color: #fefefe;
      margin: 5% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 70%;
      max-height: 80vh;
      overflow-y: auto;
      border-radius: 5px;
    }

    .history-table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }

    .history-table th, .history-table td {
      border: 1px solid #ddd;
      padding: 10px;
      text-align: center;
    }

    .history-table th {
      background-color: #f2f2f2;
    }

    .logout-btn {
      background-color: #f44336;
      color: white;
      border: none;
      padding: 10px 15px;
      border-radius: 4px;
      cursor: pointer;
      float: right;
    }

    .logout-btn:hover {
      background-color: #d32f2f;
    }
  </style>
</head>
<body>

<%
  String currentUsername = (String) session.getAttribute("username");
  String currentRole = (String) session.getAttribute("user_role");

  if (currentUsername == null || !"admin".equals(currentRole)) {
    response.sendRedirect("index.jsp");
    return;
  }
%>

<!-- 顶部导航 -->
<div class="header">
  <div class="username">
    <%= currentUsername %>
    <span class="role-tag">(管理员)</span>
  </div>
  <button class="edit-btn" id="adminEditBtn">修改信息</button>
</div>

<!-- 用户分类选项卡 -->
<div class="user-tabs">
  <button class="tab-btn active" data-role="user">普通用户</button>
  <button class="tab-btn" data-role="admin">管理员</button>
</div>

<!-- 用户列表容器 -->
<div class="user-list-container">
  <div class="user-list" id="userListContainer">
    <!-- 用户列表将通过JS动态加载 -->
  </div>
</div>

<button class="logout-btn" onclick="logout()">退出登录</button>

<!-- 管理员信息修改模态框 -->
<div id="adminEditModal" class="modal">
  <div class="modal-content">
    <span class="close" onclick="closeAdminEditModal()">&times;</span>
    <h2>修改管理员信息</h2>
    <form id="adminEditForm">
      <div class="form-group">
        <label for="adminUsername">用户名:</label>
        <input type="text" id="adminUsername" name="username" value="<%= currentUsername %>" required>
      </div>
      <div class="form-group">
        <label for="adminEmail">邮箱:</label>
        <input type="email" id="adminEmail" name="email" required>
      </div>
      <div class="form-group">
        <label for="adminPhone">电话:</label>
        <input type="tel" id="adminPhone" name="phone" required>
      </div>
      <button type="button" class="save-btn" onclick="saveAdminInfo()">保存修改</button>
    </form>
  </div>
</div>

<!-- 用户信息修改模态框 -->
<div id="userEditModal" class="modal">
  <div class="modal-content">
    <span class="close" onclick="closeUserEditModal()">&times;</span>
    <h2>修改用户信息</h2>
    <form id="userEditForm">
      <input type="hidden" id="editUsername" name="username">
      <div class="form-group">
        <label for="userEmail">邮箱:</label>
        <input type="email" id="userEmail" name="email" required>
      </div>
      <div class="form-group">
        <label for="userPhone">电话:</label>
        <input type="tel" id="userPhone" name="phone" required>
      </div>
      <button type="button" class="save-btn" onclick="saveUserInfo()">保存修改</button>
    </form>
  </div>
</div>

<!-- 用户历史记录模态框 -->
<div id="historyModal" class="history-modal">
  <div class="history-content">
    <span class="close" onclick="closeHistoryModal()">&times;</span>
    <h2 id="historyTitle">用户历史记录</h2>
    <table class="history-table">
      <thead>
      <tr>
        <th>时间</th>
        <th>视频名称</th>
        <th>受灾建筑</th>
        <th>受灾人数</th>
        <th>受灾树木</th>
      </tr>
      </thead>
      <tbody id="historyBody">
      <!-- 历史记录将通过JS动态加载 -->
      </tbody>
    </table>
  </div>
</div>

<script>
  // 确保所有必需函数已定义
  if(!window.handleResponse) {
    window.handleResponse = function(response) {
      if (!response.ok) {
        throw new Error('网络响应不正常');
      }
      return response.json();
    };
  }

  // 定义全局函数
  window.loadUsers = function(role = 'user') {
    console.log('[DEBUG] Start loading user list, role:', role);

    // 构建请求URL
    const url = "getUserInfoServlet?action=getUsersByRole&role=" + encodeURIComponent(role);
    console.log('[DEBUG] Request URL:', url);

    fetch(url)
            .then(response => {
              console.log('[DEBUG] 收到响应，状态码:', response.status);

              if (!response.ok) {
                // 如果响应不正常，尝试获取错误信息
                return response.json().then(errData => {
                  const errorMsg = errData.error || '网络响应不正常';
                  console.error('[ERROR] 服务器返回错误:', errorMsg);
                  throw new Error(errorMsg);
                }).catch(() => {
                  throw new Error(`HTTP错误! 状态码: ${response.status}`);
                });
              }
              return response.json();
            })
            .then(data => {
              console.log('[DEBUG] 解析后的数据:', data);

              const container = document.getElementById('userListContainer');
              if (!container) {
                console.error('[ERROR] 用户列表容器未找到');
                throw new Error('页面元素缺失');
              }

              // 清空容器
              container.innerHTML = '';

              // 检查数据有效性
              if (!data || !data.users || data.users.length === 0) {
                const noDataMsg = document.createElement('p');
                noDataMsg.className = 'no-data';
                noDataMsg.textContent = '暂无用户数据';
                container.appendChild(noDataMsg);
                console.log('[DEBUG] 无用户数据返回');
                return;
              }

              // 创建表格
              const table = document.createElement('table');
              table.className = 'user-table';
              table.innerHTML = `
                <thead>
                    <tr>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>电话</th>
                        <th>角色</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="userListBody"></tbody>
            `;
              container.appendChild(table);

              // 填充数据
              const tbody = document.getElementById('userListBody');
              data.users.forEach(user => {
                const row = document.createElement('tr');

                // 用户名列（带查看历史链接）
                const nameCell = document.createElement('td');
                const nameLink = document.createElement('a');
                nameLink.href = 'javascript:void(0)';
                nameLink.className = 'user-link';
                nameLink.textContent = user.username;
                nameLink.onclick = () => showUserHistory(user.username);
                nameCell.appendChild(nameLink);

                // 邮箱列
                const emailCell = document.createElement('td');
                emailCell.textContent = user.email || '-';

                // 电话列
                const phoneCell = document.createElement('td');
                phoneCell.textContent = user.phone || '-';

                // 角色列
                const roleCell = document.createElement('td');
                roleCell.textContent = user.user_role === 'admin' ? '管理员' : '普通用户';

                // 操作列
                const actionCell = document.createElement('td');
                const editBtn = document.createElement('button');
                editBtn.className = 'user-edit-btn';
                editBtn.textContent = '编辑';
                editBtn.onclick = (e) => {
                  e.stopPropagation();
                  editUser(user.username, user.email, user.phone);
                };
                actionCell.appendChild(editBtn);

                // 组装行
                row.appendChild(nameCell);
                row.appendChild(emailCell);
                row.appendChild(phoneCell);
                row.appendChild(roleCell);
                row.appendChild(actionCell);

                tbody.appendChild(row);
              });

              console.log('[DEBUG] 用户列表加载完成，共加载', data.users.length, '个用户');
            })
            .catch(error => {
              console.error('[ERROR] 加载用户列表失败:', error);

              const container = document.getElementById('userListContainer');
              if (container) {
                const errorMsg = document.createElement('p');
                errorMsg.className = 'error-msg';
                errorMsg.textContent = `加载用户列表失败: ${error.message}`;
                container.appendChild(errorMsg);
              }

              alert(`加载用户列表失败: ${error.message}`);
            });
  };

  // 模态框操作
  const modalFunctions = {
    openAdminEditModal: () => {
      console.log('Opening admin edit modal');
      const modal = document.getElementById('adminEditModal');
      if(modal) modal.style.display = 'block';
    },
    closeAdminEditModal: () => {
      const modal = document.getElementById('adminEditModal');
      if(modal) modal.style.display = 'none';
    },
    openUserEditModal: () => {
      const modal = document.getElementById('userEditModal');
      if(modal) modal.style.display = 'block';
    },
    closeUserEditModal: () => {
      const modal = document.getElementById('userEditModal');
      if(modal) modal.style.display = 'none';
    },
    closeHistoryModal: () => {
      const modal = document.getElementById('historyModal');
      if(modal) modal.style.display = 'none';
    }
  };

  // 绑定全局函数
  Object.assign(window, modalFunctions);

  // 页面初始化
  function initPage() {
    console.log('Initializing admin page');

    // 确保DOM元素存在
    const adminEditBtn = document.getElementById('adminEditBtn');
    if(adminEditBtn) {
      adminEditBtn.addEventListener('click', openAdminEditModal);
    } else {
      console.error('未找到adminEditBtn元素');
    }

    // 修改选项卡点击事件处理
    const tabButtons = document.querySelectorAll('.tab-btn');
    if(tabButtons && tabButtons.length > 0) {
      tabButtons.forEach(btn => {
        btn.addEventListener('click', function() {
          const role = this.getAttribute('data-role');
          if(role) {
            // 确保传递有效的role值
            const validRole = role === 'admin' ? 'admin' : 'user';
            loadUsers(validRole);

            // UI状态切换
            document.querySelectorAll('.tab-btn').forEach(b => {
              b.classList.remove('active');
            });
            this.classList.add('active');
          }
        });
      });
    }

    // 初始化加载
    fetchAdminInfo();
    loadUsers('user');
  }

  // 确保DOM加载完成
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initPage);
  } else {
    initPage();
  }

  // 其他功能函数保持不变...
  function fetchAdminInfo() {
    fetch('getUserInfoServlet?username=<%= currentUsername %>')
            .then(handleResponse)
            .then(data => {
              const emailInput = document.getElementById('adminEmail');
              const phoneInput = document.getElementById('adminPhone');
              if(emailInput && phoneInput) {
                emailInput.value = data.email || '';
                phoneInput.value = data.phone || '';
              }
            })
            .catch(error => {
              console.error('Error:', error);
              alert('获取管理员信息失败: ' + error.message);
            });
  }

  function showUserHistory(username) {
    const title = document.getElementById('historyTitle');
    const tbody = document.getElementById('historyBody');
    if(!title || !tbody) return;

    title.textContent = `${username}的历史记录`;
    tbody.innerHTML = '';

    fetch(`getUserHistoryServlet?username=${username}`)
            .then(handleResponse)
            .then(data => {
              if (!data || data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5">暂无历史记录</td></tr>';
              } else {
                data.forEach(item => {
                  const row = document.createElement('tr');
                  row.innerHTML = `
              <td>${item.analysis_time || '无记录'}</td>
              <td>${item.video_name}</td>
              <td>${item.damaged_building}</td>
              <td>${item.damaged_person}</td>
              <td>${item.damaged_tree}</td>
            `;
                  tbody.appendChild(row);
                });
              }

              const modal = document.getElementById('historyModal');
              if(modal) modal.style.display = 'block';
            })
            .catch(error => {
              console.error('Error:', error);
              alert('获取历史记录失败: ' + error.message);
            });
  }

  function editUser(username, email, phone) {
    const usernameInput = document.getElementById('editUsername');
    const emailInput = document.getElementById('userEmail');
    const phoneInput = document.getElementById('userPhone');

    if(usernameInput && emailInput && phoneInput) {
      usernameInput.value = username;  // 确保这里设置值
      emailInput.value = email || '';
      phoneInput.value = phone || '';
      openUserEditModal();
    } else {
      console.error('表单元素未找到');
    }
  }

  function saveAdminInfo() {
    const form = document.getElementById('adminEditForm');
    if(!form) return;

    const formData = new FormData(form);
    fetch('updateUserServlet', {
      method: 'POST',
      body: formData
    })
            .then(response => {
              if (!response.ok) throw new Error('更新失败');
              return response.text();
            })
            .then(message => {
              alert(message);
              closeAdminEditModal();
              location.reload();
            })
            .catch(error => {
              alert('更新失败: ' + error.message);
            });
  }

  function saveUserInfo() {
    // 获取表单元素
    const form = document.getElementById('userEditForm');
    if (!form) {
      console.error('错误：未找到用户编辑表单');
      alert('系统错误：无法找到表单');
      return;
    }

    // 创建表单数据对象
    const formData = new FormData(form);

    // 调试：打印表单数据到控制台
    console.log('=== 表单提交数据 ===');
    for (let [key, value] of formData.entries()) {
      console.log(key + ': ' + value);
    }

    // 验证必填字段
    const username = formData.get('username');
    const email = formData.get('email');
    const phone = formData.get('phone');

    if (!username || username.trim() === '') {
      alert('错误：用户名不能为空');
      return;
    }

    if (!email || email.trim() === '') {
      alert('错误：邮箱不能为空');
      return;
    }

    if (!phone || phone.trim() === '') {
      alert('错误：电话不能为空');
      return;
    }

    // 显示加载状态
    const saveBtn = form.querySelector('.save-btn');
    if (saveBtn) {
      saveBtn.disabled = true;
      saveBtn.textContent = '保存中...';
    }

    // 发送请求
    fetch('updateUserServlet', {
      method: 'POST',
      body: new URLSearchParams(formData), // 使用URLSearchParams确保正确编码
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
            .then(response => {
              // 恢复按钮状态
              if (saveBtn) {
                saveBtn.disabled = false;
                saveBtn.textContent = '保存修改';
              }

              if (!response.ok) {
                // 尝试获取错误信息
                return response.text().then(text => {
                  throw new Error(text || '更新失败，状态码: ' + response.status);
                });
              }
              return response.text();
            })
            .then(message => {
              // 显示成功消息
              alert(message);

              // 关闭模态框
              closeUserEditModal();

              // 根据当前页面决定刷新方式
              if (document.getElementById('userListContainer')) {
                // 管理员页面 - 重新加载用户列表
                const activeTab = document.querySelector('.tab-btn.active');
                if (activeTab) {
                  const role = activeTab.getAttribute('data-role') || 'user';
                  loadUsers(role);
                }
              } else {
                // 个人资料页面 - 完全刷新
                location.reload();
              }
            })
            .catch(error => {
              console.error('更新用户信息失败:', error);
              alert('更新失败: ' + error.message);

              // 恢复按钮状态
              if (saveBtn) {
                saveBtn.disabled = false;
                saveBtn.textContent = '保存修改';
              }
            });
  }

  function logout() {
    if (confirm('确定要退出登录吗？')) {
      fetch('logoutServlet', {
        method: 'POST'
      })
              .then(() => {
                window.location.href = 'index.jsp';
              })
              .catch(error => {
                alert('退出登录失败: ' + error.message);
              });
    }
  }
</script>


</body>
</html>

